<script lang="ts" setup>
import {
  queryQuestionGroupTreeApi,
  saveQuestionGroupApi,
  delQuestionGroupApi,
  updloadQuestionApi,
  delQuestionApi,
  updateQuestionApi,
  questionMoveApi,
} from "@/api/activity";
import { ElMessageBox } from "element-plus";
import exportData from "@/components/exportData/exportData.vue";
const props = defineProps({
  selection: {
    type: Array,
    default: () => {
      return [];
    },
  },
  mode: {
    type: String,
    default: "page",
  },
});
const showExportData = ref(false)
const loading = ref(false),
  showExportDialog = ref(false),
  submitLoading = ref(false),
  showQuestionDialog = ref(false),
  showGroupDialog = ref(false),
  groupDialogTitle = ref(""),
  groupFormData: any = ref({
    parentId: "",
    nodeType: 1,
  }),
  tableForm: any = ref({ groupIds: [] }),
  exportForm: any = ref({ override: 1, file: "" }),
  treeData = ref<Array<any>>([]),
  treeSelectData = ref<Array<any>>([]),
  questionForm: any = ref({}),
  batchGroupDialog = ref(false),
  batchGroupForm: any = ref({}),
  selectionRow = ref(props.selection);

const groupFormRef = ref(),
  LeftTreeRef = ref(),
  uploadRef = ref(),
  tabelRef = ref(),
  questionFormRef = ref(),
  exportFormRef = ref(),
  batchGroupRef = ref();

const rules = {
    name: [{ required: true, message: "请输入分组名称", trigger: "blur" }],
    groupId: [{ required: true, message: "请选择分组", trigger: "change" }],
    file: [{ required: true, message: "请上传文件", trigger: "change" }],
  },
  questionType = {
    0: { label: "单选", tag: "" },
    1: { label: "多选", tag: "warning" },
  };

let tableData: Array<any> = [];

// 获取节点id
const getTreeNodeId = (data: any) => {
  if (data.nodeType == 1 && data.children) {
    LeftTreeRef.value.setCurrentKey(tableForm.value.groupIds[0] || ""); // 设置选中
    return;
  }
  if (data.id == "all") {
    tableForm.value.groupIds = [];
    return;
  }
  tableForm.value.groupIds = [data.id];
};

// 获取左侧的树结构
const getTagGroupTree = async () => {
  let rs = await queryQuestionGroupTreeApi({
    // insIds: tableForm.value.insIds,
    scene: "QUESTION",
  });
  if (rs.code === 200) {
    treeData.value = [
      {
        id: "all",
        name: "全部",
        children: [],
      },
    ].concat(rs.payload);
    treeSelectData.value = rs.payload;
  }
};

// 新增组
const createTagGroup = (parent?: any) => {
  groupDialogTitle.value = "新建分组";
  if (groupFormRef.value) {
    groupFormRef.value.resetFields();
    groupFormData.value = {
      parentId: parent ? parent.id : "",
      nodeType: 1,
    };
  }
  showGroupDialog.value = true;
};

// 编辑组
const editGroup = async (data: any) => {
  groupDialogTitle.value = `编辑分组【${data.name}】`;
  if (groupFormRef.value) {
    groupFormRef.value.resetFields();
  }
  groupFormData.value = {
    ...data,
    parentId: data.parentId ? data.parentId : "",
  };
  showGroupDialog.value = true;
};

const delGroup = (data: any) => {
  ElMessageBox.confirm(`是否删除【${data.name}】`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let rs = await delQuestionGroupApi({ id: data.id });
    if (rs.code === 200) {
      ElMessage.success("删除成功");
      if (data.id == tableForm.value.groupIds[0]) {
        tableForm.value.groupIds = [];
      }
      LeftTreeRef.value.removeTreeNode(data); // 删除树节点的数据
    }
  });
};

const submitGroupForm = () => {
  groupFormRef.value.validate(async (valid: any) => {
    if (valid) {
      submitLoading.value = true;
      let rs = await saveQuestionGroupApi({
        ...groupFormData.value,
        scene: "QUESTION",
      });
      if (rs.code == 200) {
        showGroupDialog.value = false;
        ElMessage.success(
          `${groupFormData.value["id"] ? "编辑" : "添加"}分类成功`
        );
        await getTagGroupTree();
      }
      submitLoading.value = false;
    }
  });
};

const getOptionsLength = (str: string) => {
  if (str) {
    let arr = JSON.parse(str);
    return arr.length;
  }
  return 0;
};

const onSearch = () => {
  tabelRef.value.search();
};

// 切换组织机构
const changeInsIds = (insIds: number) => {
  tableForm.value.insIds = insIds;
  tableForm.value.groupIds = [];
};

// 下载题库模板
const download = () => {
  window.location.href = "./fileTemplate/question.xlsx";
};

const openExport = () => {
  if (uploadRef.value) uploadRef.value.clearFiles();
  exportForm.value.file = "";
  showExportDialog.value = true;
};

const upload = (e: any) => {
  let file = e.file;
  exportForm.value.file = file;
};

// 批量导入
const submitExportForm = async () => {
  exportFormRef.value.validate(async (valid: any) => {
    if (valid) {
      submitLoading.value = true;
      let formdata = new FormData();
      for (const key in exportForm.value) {
        if (Object.hasOwnProperty.call(exportForm.value, key)) {
          const element = exportForm.value[key];
          formdata.append(key, element);
        }
      }
      let rs = await updloadQuestionApi(formdata);
      if (rs.code === 200) {
        ElMessage.success("批量导入成功");
        showExportDialog.value = false;
        onSearch();
      }
      submitLoading.value = false;
    }
  });
};

// 添加选项
const deleteOption = (index: number) => {
  questionForm.value.options.splice(index, 1);
};

// 添加选项
const addOption = () => {
  questionForm.value.options.push({ txt: "", ans: 0 });
};

const editQuestion = (row: any) => {
  let options = JSON.parse(row.item);
  questionForm.value = {
    id: row.id,
    title: row.title,
    star: row.star,
    options,
  };
  showQuestionDialog.value = true;
};

const delQuestion = (row: any) => {
  ElMessageBox.confirm("此操作将删除该题目, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let rs = await delQuestionApi({
      id: row.id,
      groupId: tableForm.value.groupIds[0] || "",
    });
    if (rs.code == 200) {
      ElMessage.success("删除题目成功");
      onSearch();
    }
  });
};

const submitQuestion = () => {
  questionFormRef.value.validate(async (valid: any) => {
    if (valid) {
      submitLoading.value = true;
      let options = questionForm.value.options;
      let answerStr = [],
        itemStr = [];
      for (let i = 0; i < options.length; i++) {
        if (options[i].ans == 1) answerStr.push(options[i].txt);
        else itemStr.push(options[i].txt);
      }
      let rs = await updateQuestionApi(
        Object.assign(questionForm.value, {
          itemStr: itemStr.join("$$"),
          answerStr: answerStr.join("$$"),
        })
      );
      if (rs.code == 200) {
        showQuestionDialog.value = false;
        ElMessage.success(`修改成功`);
        onSearch();
      }
      submitLoading.value = false;
    }
  });
};

const onTableLoaded = (list: Array<any>) => {
  tableData = list;
  setSelect();
};

// 行选中切换
const onSelectChange = (rows: Array<any>, row: any) => {
  if (!row) return;
  let selectionIndex = selectionRow.value.findIndex(
    (item) => row.id == item.id
  );
  // 若存在则移除该数据
  if (selectionIndex >= 0) selectionRow.value.splice(selectionIndex, 1);
  // 选中
  else {
    selectionRow.value.push(row);
  }
};

// 全选
const oneSelectAll = (rows: Array<any>) => {
  rows.forEach((row) => {
    let index = selectionRow.value.findIndex((item) => item.id == row.id);
    if (index < 0) selectionRow.value.push(row);
  });
  if (rows.length == 0) {
    tableData.forEach((row) => {
      let index = selectionRow.value.findIndex((item) => item.id == row.id);
      if (index >= 0) selectionRow.value.splice(index, 1);
    });
  }
};

// 返回选中数据
const getSelect = () => {
  return selectionRow.value;
};

// 设置选中数据
const setSelect = () => {
  nextTick(() => {
    tableData.forEach((item) => {
      let index = selectionRow.value.findIndex((row) => row.id == item.id);
      if (index >= 0) {
        tabelRef.value.toggleRowSelection(item, true);
      } else {
        tabelRef.value.toggleRowSelection(item, false);
      }
    });
  });
};

// 批量移动分组
const batchMoveGroup = () => {
  if (selectionRow.value.length == 0) {
    ElMessage.warning("请先选择需要修改的分组");
    return;
  }
  batchGroupForm.value = {
    ids: selectionRow.value.map((item) => item.id),
  };
  batchGroupDialog.value = true;
};

const submitBatchGroup = () => {
  batchGroupRef.value.validate(async (valid: any) => {
    if (valid) {
      submitLoading.value = true;
      let rs = await questionMoveApi(batchGroupForm.value);
      if (rs.code == 200) {
        batchGroupDialog.value = false;
        ElMessage.success(`修改成功`);
        selectionRow.value = [];
        onSearch();
      }
      submitLoading.value = false;
    }
  });
};
const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    getTagGroupTree();
    if(tableForm.value.groupIds != []){
      tableForm.value.groupIds = [];
    }
    else onSearch()
  },
  {
    deep: true
  }
)
onMounted(() => {
  getTagGroupTree();
});

defineExpose({ getSelect, setSelect });
</script>
<script lang="ts">
export default {
  name: 'QuestionBank'
}
</script>
<template>
  <main-content
    title="题库管理"
    :inner-padding="false"
    class="category-main-content"
  >
    <l-r-content-index v-loading="loading">
      <template #title>
        <div class="side-title-inner">
          题库分组
          <el-button type="primary" @click="createTagGroup">
            <el-icon>
              <Plus />
            </el-icon>
            <span style="margin-left: 10px">新增分组</span>
          </el-button>
        </div>
      </template>
      <template #side-content>
        <LeftTree
          ref="LeftTreeRef"
          :treeData="treeData"
          :disableSelect="false"
          :currentNodeKey="tableForm.groupIds[0] || 'all'"
          showAdd="nodeType"
          :buttonAdd="['2404']"
          :buttonEdit="['2405']"
          :buttonDel="['2406']"
          @getTreeNodeId="getTreeNodeId"
          @add="createTagGroup"
          @edit="editGroup"
          @del="delGroup"
        ></LeftTree>
      </template>
      <MainContentSearchBarWrapper>
        <SearchBar inline>
          <template #normal>
            <!--            <ins-cascader-filter @change="changeInsIds"></ins-cascader-filter>-->
          </template>
          <template #toolbar>
            <el-form-item>
              <el-button v-if="mode === 'page'" type="primary" @click="batchMoveGroup"
                >批量修改分组</el-button
              >
              <el-button v-has="['2401']" type="primary" @click="openExport"
                >批量导入</el-button
              >
               <!-- TODO 加权限 -->
              <el-button type="primary" @click="showExportData = true">导出</el-button>
            </el-form-item>
          </template>
        </SearchBar>
        <LayoutTable
          ref="tabelRef"
          url="/activity/question/queryPage"
          :param="tableForm"
          row-key="id"
          @select="onSelectChange"
          @select-all="oneSelectAll"
          @loaded="onTableLoaded"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            prop="title"
            label="题目名称"
            align="center"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column label="类型" min-width="80">
            <template #default="scope">
              <el-tag :type="questionType[scope.row.type].tag">
                {{ questionType[scope.row.type].label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="答案数量/选项数量"
            align="center"
            min-width="140"
          >
            <template #default="scope"
              >{{ scope.row.answerCount }}/{{
                getOptionsLength(scope.row.item)
              }}</template
            >
          </el-table-column>
          <el-table-column
            prop="star"
            label="题目难度"
            align="center"
            min-width="100"
          />
          <el-table-column
            prop="creatorName"
            label="创建人"
            align="center"
            min-width="100"
          />
          <el-table-column label="创建时间" align="center" min-width="160"
            ><template #default="scope">
              <div>
                {{ $filters.dateFormat(scope.row.createTime) }}
              </div>
            </template></el-table-column
          >
          <el-table-column
            prop="quoteCount"
            label="引用数量"
            align="center"
            min-width="100"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="100"
            fixed="right"
          >
            <template #default="scope">
              <div>
                <el-button
                  v-has="['2402']"
                  type="primary"
                  link
                  @click="editQuestion(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-has="['2403']"
                  @click="delQuestion(scope.row)"
                  type="primary"
                  link
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </LayoutTable>
      </MainContentSearchBarWrapper>
    </l-r-content-index>
  </main-content>
  <Dialog
    title="批量导入题目"
    v-model="showExportDialog"
    :loading="submitLoading"
    :width="500"
    @confirm="submitExportForm"
  >
    <div class="uploadExcel">
      <div class="tips">
        点击下载<span @click="download">Excel表格模板</span>
      </div>
      <el-form
        ref="exportFormRef"
        :model="exportForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="重复题目处理：" prop="override">
          <el-select v-model="exportForm.override" placeholder="请选择">
            <el-option label="覆盖已有数据" :value="1" />
            <el-option label="保留已有数据" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属分组：" prop="groupId">
          <TreeSelect
            v-model="exportForm.groupId"
            :treeSelectData="treeSelectData"
            :expand-on-click-node="false"
            :check-strictly="true"
            :treeProps="{ label: 'name', disabled: ((data: any)=>{ return data.nodeType===1 }) }"
            placeholder="请选择分组"
          ></TreeSelect>
        </el-form-item>
        <el-form-item label-width="0" prop="file">
          <el-upload
            ref="uploadRef"
            class="upload"
            drag
            :limit="1"
            action=""
            accept=".xlsx,.xls"
            :show-file-list="true"
            :http-request="upload"
          >
            <div class="uploadSlot">
              <p>点击或文件拖拽到这里上传</p>
              <div class="uploadSlot-tip">
                *仅支持xlsx格式，请将大小控制在20M以内
              </div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
  </Dialog>
  <Dialog
    v-model="showGroupDialog"
    :title="groupDialogTitle"
    :loading="submitLoading"
    :width="500"
    @confirm="submitGroupForm"
  >
    <el-form
      :model="groupFormData"
      :rules="rules"
      ref="groupFormRef"
      label-width="120px"
    >
      <el-form-item label="分组名称" prop="name">
        <el-input
          type="text"
          placeholder="请输入分组名称"
          clearable
          maxlength="30"
          :show-word-limit="true"
          v-model="groupFormData.name"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="所属上级">
        <TreeSelect
          v-model="groupFormData.parentId"
          :treeSelectData="treeSelectData"
          :expand-on-click-node="false"
          :check-strictly="true"
          :treeProps="{ label: 'name', disabled: ((data: any)=>{ return data.nodeType===0 }) }"
          placeholder="所属上级非必填"
        ></TreeSelect>
      </el-form-item>
      <el-form-item label="是否有下级分组" prop="exit">
        <el-radio-group
          v-model="groupFormData.nodeType"
          :disabled="groupFormData['id']"
        >
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </Dialog>
  <Dialog
    v-model="showQuestionDialog"
    title="编辑题目"
    :loading="submitLoading"
    :width="500"
    @confirm="submitQuestion"
  >
    <el-form
      :model="questionForm"
      :rules="rules"
      ref="questionFormRef"
      label-width="auto"
    >
      <el-form-item label="题目" prop="title">
        <el-input
          type="text"
          placeholder="请输入题目"
          clearable
          v-model="questionForm.title"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="难度">
        <el-rate v-model="questionForm.star" />
      </el-form-item>
      <el-form-item label="选项">
        <div>
          <el-form-item
            label-width="0"
            v-for="(option, oIndex) in questionForm.options"
            :prop="`options.${oIndex}`"
            :rules="[
              {
                required: true,
                message: '请填写选项',
                trigger: 'blur',
              },
            ]"
            class="flex-container"
          >
            <el-input
              v-model="questionForm.options[oIndex].txt"
              placeholder="请输入"
              style="width: 300px"
            />
            <el-switch
              v-model="questionForm.options[oIndex].ans"
              inline-prompt
              :active-value="1"
              :inactive-value="0"
              active-text="正确"
              inactive-text="错误"
              style="margin-left: 10px"
            />
            <el-button
              type="primary"
              icon="delete"
              circle
              style="margin-left: 10px"
              @click="deleteOption(oIndex)"
            ></el-button>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item v-if="questionForm.options.length < 8">
        <el-button type="primary" icon="plus" @click="addOption"
          >添加选项</el-button
        >
      </el-form-item>
    </el-form>
  </Dialog>
  <!-- 批量修改分组 -->
  <Dialog
    v-model="batchGroupDialog"
    :title="`选择分组`"
    :loading="submitLoading"
    :width="500"
    @confirm="submitBatchGroup"
  >
    <el-form
      ref="batchGroupRef"
      :model="batchGroupForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="重复题目处理：" prop="override">
        <el-select v-model="batchGroupForm.override" placeholder="请选择">
          <el-option label="覆盖已有数据" :value="1" />
          <el-option label="保留已有数据" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="分组" prop="groupId">
        <TreeSelect
          v-model="batchGroupForm.groupId"
          :treeSelectData="treeSelectData"
          :expand-on-click-node="false"
          :check-strictly="true"
          :treeProps="{ label: 'name', disabled: ((data: any)=>{ return data.nodeType===1 }) }"
          placeholder="请选择分组"
        ></TreeSelect>
      </el-form-item>
    </el-form>
  </Dialog>
  <exportData
      v-model:show-dialog="showExportData"
      title="题库管理"
      export-type="activityQuestionExport"
    >
    </exportData>
</template>

<style scoped lang="scss">
.side-title-inner {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.category-item {
  margin-top: 6px;

  .rank-item {
    display: flex;
    align-items: center;

    .name {
      font-size: 14px;
      font-weight: 500;
      color: var(--el-color-primary);
      margin-bottom: 5px;
    }

    .desc {
      font-size: 12px;
      color: var(--el-color-info-dark-2);
    }
  }

  .left {
    width: 50px;
    height: 50px;
    margin-right: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #eee;
    overflow: hidden;
    border-radius: 5px;
  }

  .right {
    flex: 1;
  }
}

:deep(.main-content-tab-bar-wrapper) {
  margin-bottom: 0;
}

.tips {
  font-size: 12px;
  font-weight: 400;
  color: #999999;
  line-height: 17px;
  margin-bottom: 8px;
  padding-left: 5px;
  span {
    color: #6178ff;
    cursor: pointer;
  }
}
.upload {
  width: 412px;
  margin-top: 20px;
  :deep(.el-upload-dragger) {
    width: 100%;
    border: 0;
    padding: 0;

    // border-bottom: 1px solid #dae0ff;
  }
}
.uploadSlot {
  width: 100%;
  height: 85px;
  background: url(@/assets/images/_upload_icon.png) center / 100% no-repeat;
  padding-top: 102px;
  text-align: center;
  p {
    font-size: 16px;
    color: #333333;
    line-height: 24px;
    margin-bottom: 4px;
  }
  &-tip {
    font-size: 14px;
    font-weight: 400;
    color: #999999;
    line-height: 22px;
  }
}

.flex-container {
  display: flex;
  align-items: center;
  &.flex-container {
    margin-top: 10px;
  }
}
</style>
